﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fintech.Utils.Database;
using ZOVNP.Model;
using ZOVNP.Model.Abstracts;

namespace ZOVNP.WinView.Workplaces.Administrator
{
    public partial class PriceEditorControl : UserControl
    {
        private Workspace _workspace;

        private SplitContainer _sc;

        private TreeView _tv;
        private TreeNodeCollection _rootNodeCollection;

        private DataGridView _dgv;

        public PriceEditorControl(Workspace workspace)
        {
            _workspace = workspace;

            InitializeComponent();

            // ==== SplitContainer ====
            _sc = new SplitContainer();
            _sc.Orientation = Orientation.Vertical;
            _sc.FixedPanel = FixedPanel.Panel1;
            _sc.Dock = DockStyle.Fill;
            _sc.SplitterDistance = this.Width/4;
            Controls.Add(_sc);

            // ==== TreeView ====
            _tv = new TreeView();
            _tv.Dock = DockStyle.Fill;
            var root = new TreeNode(workspace.Engine.CurrentUser.Name);
            _rootNodeCollection = root.Nodes;
            _tv.Nodes.Add(root);
            _sc.Panel1.Controls.Add(_tv);


            using (var context = _workspace.Engine.CreateContext())
            {
                var productTypes = context.Query<IProductType>().Include(pt => pt.ProductTypes).Where(pt => pt.ParentProductType == null).ToArray();
                PopulateTree(productTypes);
            }
            //var productTypes = _workspace.GetAllProductTypes();
            //PopulatePriceParts(productTypes);

            _tv.AfterSelect += AfterTreeNodeSelect;
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (_sc != null)
                _sc.SplitterDistance = this.Width/4;
        }

        private void PopulateTree(IEnumerable<IProductType> productTypes)
        {
            _rootNodeCollection.Clear();

            foreach (var productType in productTypes)
            {
                var productTypeNode = new ProductTypeNode(productType);
                _rootNodeCollection.Add(productTypeNode);

                PopulateTreeRec(productTypeNode);
            }
        }

        private void PopulateTreeRec(ProductTypeNode node)
        {
            foreach (var productType in node.ProductType.ProductTypes)
            {
                var productTypeNode = new ProductTypeNode(productType);
                node.Nodes.Add(productTypeNode);
                PopulateTreeRec(productTypeNode);
            }

            foreach (var product in _workspace.GetProductsOfType(node.ProductType.ID))
            {
                var productNode = new ProductNode(product);
                node.Nodes.Add(productNode);
            }
        }

        private void AfterTreeNodeSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node is ProductTypeNode)
            {
                Guid productTypeId = ((ProductTypeNode) e.Node).ProductType.ID;
                using (var context = _workspace.Engine.CreateContext())
                {
                    //var priceItems = context.Query<IPriceItem>().Include(pi => pi.Product).Include(pi => pi.Material).Where(pi => pi.Product.ProductType.ID == productTypeId).ToArray();
                    var priceItems = context.ExecuteProcedure<IPriceItem>("GetPriceItemsForProductTypeAndChilds", new Parameter("rootProductType_ID", productTypeId));
                    PopulateGrid(priceItems);
                }
            }
            else if (e.Node is ProductNode)
            {
                Guid productId = ((ProductNode) e.Node).Product.ID;
                using (var context = _workspace.Engine.CreateContext())
                {
                    var priceItems = context.Query<IPriceItem>().Include(pi => pi.Product).Include(pi => pi.Material).Where(pi => pi.Product.ID == productId).ToArray();
                    PopulateGrid(priceItems);
                }
            }
            else
            {
                PopulateGrid(null);
            }
        }

        private void PopulateGrid(IEnumerable<IPriceItem> priceItems)
        {
            if (_dgv != null)
            {
                _sc.Panel2.Controls.Remove(_dgv);
                _dgv.Dispose();
                _dgv = null;
            }

            if (priceItems != null)
            {
                _dgv = new DataGridView();
                var textBoxTemplate = new DataGridViewTextBoxCell();
                _dgv.Columns.Add(new DataGridViewColumn(textBoxTemplate) {Name = "ProductName", HeaderText = "Продукт"});
                _dgv.Columns.Add(new DataGridViewColumn(textBoxTemplate) {Name = "MaterialName", HeaderText = "Материал"});
                _dgv.Columns.Add(new DataGridViewColumn(textBoxTemplate) {Name = "Color", HeaderText = "Цвет"});
                _dgv.Columns.Add(new DataGridViewColumn(textBoxTemplate) {Name = "Cost", HeaderText = "Стоимость"});

                _dgv.Dock = DockStyle.Fill;
                _sc.Panel2.Controls.Add(_dgv);

                foreach (var priceItem in priceItems)
                {
                    DataGridViewRow row = new DataGridViewRow();
                    row.CreateCells(_dgv);
                    row.Cells[_dgv.Columns["ProductName"].Index].Value = priceItem.Product.Name;
                    row.Cells[_dgv.Columns["MaterialName"].Index].Value = priceItem.Material != null ? priceItem.Material.Name : string.Empty;
                    row.Cells[_dgv.Columns["Color"].Index].Value = priceItem.Color;
                    row.Cells[_dgv.Columns["Cost"].Index].Value = priceItem.Cost;
                    row.Tag = priceItem;
                    _dgv.Rows.Add(row);
                }
            }
        }
    }
}
